<template>
  <el-dialog width="1000" v-model="visible" :title="!dataForm.dishId ? $t('add') : $t('update')"
    :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
      label-width="120px">
      <el-form-item label="菜品名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="菜品名称"></el-input>
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-popover :width="400" ref="categoriesListPopover" placement="bottom-start" trigger="click"
          popper-class="popover-pop">
          <template v-slot:reference>
            <el-input v-model="dataForm.categoryName" :readonly="true" placeholder="分类">
              <template v-slot:suffix>
                <el-icon @click.stop="clearDefaultHandle()" class="el-input__icon"><circle-close /></el-icon>
              </template> </el-input></template>
          <div class="popover-pop-body">
            <el-tree :data="categoriesList" :props="{ label: 'name', children: 'children' }" node-key="id"
              ref="categoriesTree" :highlight-current="true" :expand-on-click-node="false" accordion
              @current-change="currentChangeHandle">
            </el-tree>
          </div>
        </el-popover>
      </el-form-item>
      <el-form-item label="口味" prop="dishFlavorId">
        <flavor :dishId="dataForm.dishId" ref="flavorRef" @update:flavorLists="updaFlavorLists" />
      </el-form-item>
      <el-form-item label="物料配置" prop="skuLists">
        <materials-list :specType="1" :dishId="dataForm.dishId" ref="materialRef"
          @update:materialsLists="updateMaterialLists" />
      </el-form-item>
      <el-form-item label="规格配置" prop="skuLists">
        <sku-list :specType="0" :dishId="dataForm.dishId" ref="skuRef" @update:skuLists="updateSkuLists" />
      </el-form-item>
      <el-form-item label="标签" prop="tagLists">
        <tags :dishId="dataForm.dishId" ref="tagRef" @update:modelValue="updatetagLists" />
      </el-form-item>
      <el-form-item label="菜品描述" prop="description">
        <tinymce-editor v-model="dataForm.description" />
        <!-- <el-input v-model="dataForm.description" placeholder="菜品描述"></el-input> -->
      </el-form-item>
      <el-form-item label="菜品价格" prop="price">
        <el-input v-model="dataForm.price" placeholder="菜品价格"></el-input>
      </el-form-item>
      <el-form-item label="菜品大图片" prop="imageUrl">
        <images ref="imagesRef" @refreshDataList="refreshDataListHandle" />
      </el-form-item>
      <el-form-item label="菜品缩略图" prop="thumbnailUrl">
        <images ref="thumimagesRef" @refreshDataList="refreshThumbnailListsHandle" />
      </el-form-item>
      <el-form-item label="在售状态" prop="isActive">
        <el-radio-group v-model="dataForm.isActive">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="就餐类型" prop="eatType">
        <ren-select :multiple="true" v-model="dataForm.eatType" dict-type="eat_type" placeholder="就餐类型"></ren-select>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
    $t("confirm")
        }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, nextTick, ref } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
import Tags from "./tags.vue";
import Flavor from "./flavor.vue";
import Images from "./images.vue";
import SkuList from "./sku-list.vue";
import MaterialsList from "./materials-list.vue";

import TinymceEditor from "@/components/tinymce";

const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const categoriesList = ref([]);
const visible = ref(false);
const dataFormRef = ref();
const categoriesListPopover = ref();

const rules = ref({
  name: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  categoryId: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  price: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  description: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  isActive: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  eatType: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  imageUrl: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  thumbnailUrl: [{ required: true, message: t("validate.required"), trigger: "blur" }],
});

const tagRef = ref();
const flavorRef = ref();
const skuRef = ref();
const materialRef = ref();
const imagesRef = ref();
const thumimagesRef = ref();

const dataForm:any = reactive({
  dishId: "",
  name: "",
  description: "",
  price: "",
  eatType: [],
  imageUrl: "",
  thumbnailUrl: "",
  isActive: "",
  categoryId: "",
  categoryName: "",
  dishFlavorId: "",
  restaurantId: "",
  createdDate: "",
  updateDate: "",
  tagLists: [], // 标签列表
  flavorLists: [], // 口味列表
  imageLists: [], // 大图
  thumbnailLists: [], // 缩略图
  skuLists: [], // sku
  materialLists: [], // sku
});

const updateHandle = (value:any) => {
  dataForm.description = value;
}

const init = async (dishId?: number) => {
  visible.value = true;
  dataForm.dishId = dishId;

  // 重置表单
  nextTick(() => {
    if (dataFormRef.value) {
      dataFormRef.value.resetFields();
    }
  });

  // 是否是编辑
  if (dishId) {
    const res = await getInfo(dishId);
    if (res.code == 200) {
      const aa = {eatType: res.data?.eatType ? (res.data?.eatType as string).split(","): []}
      Object.assign(dataForm, res.data, aa);
    }
  }
  // 1.初始化菜单 异步
  getCategoriesList();

  // 2.初始化标签 同步
  // 3.初始化口味 同步
  nextTick(() => {
    tagRef.value.init(dataForm.tagLists);
    flavorRef.value.init(dataForm.flavorLists);
    imagesRef.value.init(dataForm.dishId, 0, dataForm.imageLists);
    thumimagesRef.value.init(dataForm.dishId, 7, dataForm.thumbnailLists);
    skuRef.value.init(dataForm.skuLists);
    materialRef.value.init(dataForm.materialLists);
  });
};

const updatetagLists = (vals:any) => {
  dataForm["tagLists"] = vals;
};
const updaFlavorLists = (vals:any) => {
  dataForm["flavorLists"] = vals;
};
const updateSkuLists = (vals:any) => {
  dataForm["skuLists"] = vals;
};
const updateMaterialLists = (vals:any) => {

  dataForm["materialLists"] = vals;
};

const refreshDataListHandle = (imageLists:any) => {
  const recommendedImage = imageLists.find((item: any) => item.isRecommend === 1);
  dataForm.imageUrl = recommendedImage?.url || '';
  dataForm["imageLists"] = imageLists;
};
const refreshThumbnailListsHandle = (thumLists:any) => {
  const recommendedImage = thumLists.find((item: any) => item.isRecommend === 1);
  dataForm.thumbnailUrl = recommendedImage?.url || '';
  dataForm["thumbnailLists"] = thumLists;
};
// 删除分类
const clearDefaultHandle = () => {
  dataForm.categoryId = null;
  dataForm.categoryName = null;
};
// 分类选中
const currentChangeHandle = (data: any) => {
  dataForm.categoryId = data.id;
  dataForm.categoryName = data.name;
  categoriesListPopover.value.hide();
};
// 获取分类列表
const getCategoriesList = () => {
  return baseService.get("/sys/zycategories/list").then((res) => {
    if (res.code !== 200) {
      return ElMessage.error(res.message);
    }
    categoriesList.value = res.data;
  });
};

// 获取信息
const getInfo = async (dishId: number) => {
  return await baseService.get("/sys/dishes/destail/" + dishId);
};


// const autoValidateField = () => {
//   // 手动触发 el-form-item 的校验
//   dataFormRef.value.validateField("imageUrl", (error:any) => {
//     debugger;
//     if (error) {
//       ElMessage.error(error.message);
//     } else {
//       console.log("缩略图校验通过");
//     }
//   });
// };

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.dishId ? baseService.post : baseService.put)("/sys/dishes", Object.assign(dataForm, {eatType: dataForm.eatType.join(",")})).then(
      (res) => {
        ElMessage.success({
          message: t("prompt.success"),
          duration: 500,
          onClose: () => {
            visible.value = false;
            emit("refreshDataList");
          },
        });
      }
    );
  });
};

defineExpose({
  init,
});
</script>
